<?php
/**
 * Created by PhpStorm.
 * User: gesangdianzi
 * Date: 2019/8/25
 * Time: 10:58
 */

namespace app\channel;

use Workerman\Lib\Timer;
use Workerman\Worker;

class Command extends \yiiplus\websocket\workerman\Command
{
    /**
     * @var \Workerman\Lib\Timer 计时器
     */
    public $timer;
    /**
     * @var array 
     * [
     *  ['id'=>1,'msg'=>'这是数据']
     * ]
     */
    public $send_data = [];
    public function connect($connection)
    {
        echo '[info] new connection, fd' . $connection->id . PHP_EOL;
        
        $time_interval = 2.5;
        if(empty($this->timer)){
            $this->timer = Timer::add($time_interval,
                function()
                {
                    if(!empty($send_data)){
                        foreach ($send_data as $data) {
                            if (!$this->_server->connections[$data['id']]->send($data['msg'])) {
                                echo '[error] client_id ' . $data['id'] . ' send failure.' . PHP_EOL;
                                return false;
                            }
                            echo '[success] client_id ' . $data['id'] . ' send success.' . PHP_EOL;
                        }
                    }
//                    \Yii::getLogger()->log(print_r($this->_server->connections,true),1);exit();
                    echo "Timer run\n";
                }
            );
        }
        
    }
}